package com.nwpu.coursesupport.tool;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.nwpu.coursesupport.entity.Resource;
import com.nwpu.coursesupport.entity.Student;
import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.enumeration.StatusType;
import com.nwpu.coursesupport.mapper.StudentMapper;

public class WebUtils {
	
	@Autowired
	private StudentMapper studentMapper;
    private static Logger logger = LoggerFactory.getLogger(WebUtils.class);
	
	public static void sendFile(HttpServletResponse response, Resource resource) {

		File file = new File(resource.getUrl());
		if (file.exists()) {

			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				String fileName = URLEncoder.encode(resource.getFileName(), "UTF-8");
				response.reset();
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
				response.addHeader("Content-Length", "" + file.length());
				byte[] buffer = new byte[1024];
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	public static void sendFileFormat(HttpServletResponse response, Resource resource, String classNumber, String studentCode, String name) {
		
		File file = new File(resource.getUrl());
		if (file.exists()) {

			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				String fNC = resource.getFileName();
				String fNCf,fNCl;
				int location = fNC.lastIndexOf(".");
				fNCf = fNC.substring(0,location);
				fNCl = fNC.substring(location);
				String format = classNumber+"_"+studentCode+"_"+name;
				if(!(fNCf.endsWith(format)&&fNCf.startsWith(format))){
					fNC = format + fNCl;
				}
				String fileName = URLEncoder.encode(fNC, "UTF-8");
				
				response.reset();
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
				response.addHeader("Content-Length", "" + file.length());
				byte[] buffer = new byte[1024];
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
    
	public static void sendJson(HttpServletResponse response,StatusType status,String message){
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			JSONResult rst=new JSONResult();
			switch(status){
			case NOLOGIN:
				rst.fail();
				rst.setMessage(message);
				rst.setStatusCode(StatusType.NOLOGIN.getStatusCode());
				break;
			case NOROLE:
				rst.fail();
				rst.setMessage(message);
				rst.setStatusCode(StatusType.NOROLE.getStatusCode());
				break;
			case SUCCESS:
				rst.success();
				break;
			case WRONG:
				rst.fail();
				rst.setMessage(message);
				break;
				default:
					break;
			}
			String json=JSONUtils.obj2json(rst);
			response.getWriter().write(json);
		} /*catch (JsonProcessingException e) {
			logger.error("json解析出错");
			e.printStackTrace();
		}*/ catch (IOException e) {
			logger.error("流出错");
			e.printStackTrace();
		}finally{
			try {
				response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static boolean isAjax(HttpServletRequest request){
		String requestedWith = request.getHeader("X-Requested-With");
		if (requestedWith!=null && "XMLHttpRequest".equals(requestedWith)) {
			return true;
		}
		return false;
	}
	public static void sendFileList(HttpServletResponse response, List<Resource> relist, String path, String zipName) throws IOException {
		List<String> fname = new ArrayList<>();
		List<FileInputStream> input = new ArrayList<>();
		FileInputStream fis;
		
		for(Resource resource : relist){
			fname.add(resource.getFileName());
			fis = new FileInputStream(new File(resource.getUrl()));
			input.add(fis);
		}
/*		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");*/

		
		String pathZip = new StringBuilder().append(path).append(File.separator).append(zipName).toString();
		File zipFile = new File(pathZip);
		//设置文件为50MB
		//TODO:设置上传文件大小
		byte[] buf = new byte[1024];
		int len;
        ZipOutputStream zout=new ZipOutputStream(new FileOutputStream(zipFile));
        for (int i = 0; i < input.size(); i++) {  
            FileInputStream in =input.get(i);  
            zout.putNextEntry(new ZipEntry(fname.get(i)));    
            while ((len = in.read(buf)) > 0) {  
                zout.write(buf, 0, len);  
            }  
            zout.closeEntry();  
            in.close();  
        }
        zout.close();
        if (zipFile.exists()) {

			FileInputStream fisz = null;
			BufferedInputStream bis = null;
			try {
				String fileName = URLEncoder.encode(zipName, "UTF-8");
				response.reset();
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
				response.addHeader("Content-Length", "" + zipFile.length());
				byte[] buffer = new byte[1024];
				fisz = new FileInputStream(zipFile);
				bis = new BufferedInputStream(fisz);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fisz != null) {
					try {
						fisz.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}        
        zipFile.delete();
			
		}		
}
